package vip.yyzhu.redisadmin.aop.verifyKeyType;

import lombok.val;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import vip.yyzhu.redisadmin.jopo.ResJson;
import vip.yyzhu.redisadmin.redis.RedisList;
import vip.yyzhu.redisadmin.util.Tool;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
@Aspect
@Component
@Order(2) //定义加载 顺序，在验证连接后执行
public class VerifyKeyTypeAspect {
    @Autowired
    RedisList redisList;

    /**
     * Spring中使用@Pointcut注解来定义方法切入点
     *
     * @Pointcut 用来定义切点，针对方法  @Aspect 用来定义切面，针对类
     * 后面的增强均是围绕此切入点来完成的
     * 此处仅配置被我们刚才定义的注解：AuthToken修饰的方法即可
     */

    @Pointcut("@annotation(verifyKeyType)")
    public void doVerifyKeyType(vip.yyzhu.redisadmin.aop.verifyKeyType.VerifyKeyType verifyKeyType) {
    }

    /**
     * 此处使用环绕增强，在方法执行之前或者执行之后均会执行。
     */
    // @AuthUnique
    @Around("doVerifyKeyType(verifyKeyType)")
    public Object deBefore(ProceedingJoinPoint pjp, VerifyKeyType verifyKeyType) throws Throwable {
        // 验证key类型
        System.out.println("验证key类型");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String key = request.getParameter("key");
        if(key == null){
            return new ResJson(4000, "参数不完整");
        }
        String[] types = verifyKeyType.value();
        val jedis = Tool.getJedis(request, redisList);
        String type = jedis.type(key);
        Map res = new HashMap();
        // 不允许为空 和 type != none
        if (!verifyKeyType.empty() || !"none".equals(type)) {
            if ("none".equals(type)) {
                res.put("err", "key为 " + key + " 的数据不存在");
                return new ResJson(4041, "key不存在，有可能已经被删除", res);
            }
            if (types.length >= 1) {
                if (!Arrays.asList(types).contains(type)) {
                    res.put("err", key + "的类型为" + type);
                    return new ResJson(4018, "类型不对应，请刷新后重试", res);
                }
            }
        }

        Object proceed = pjp.proceed();
        System.out.println("验证key类型->");
        System.out.println(proceed);
        return proceed;
    }
}
